package com.feizi.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.feizi.entity.UserEntity;

public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//获取请求的uri:去除http://localhost:8080这部分，只要剩下的
		String uri=request.getRequestURI();
		
		//除了login.jsp可以公开访问，其他的都可以拦截
		if(uri.indexOf("/login.do") >= 0 ||uri.indexOf("/findProduct.do") >= 0 || uri.indexOf("/register.do") >=0 ||uri.indexOf("/getVerifiCode.do") >= 0) {
			return true;
		}
		
		//获取session
		HttpSession session = request.getSession();
		UserEntity user = (UserEntity) session.getAttribute("user");
		
		//判断session中是否有用户数据，如果有则返回true，没有继续向下执行
		if(user != null) {
//			如果登录过，就放行
			return true;
		}
		
		//不符合条件，则给出提示信息，并转发到登录页面
		request.setAttribute("msg", "您还没有登录，请先登录");
		request.getRequestDispatcher("/login.jsp").forward(request, response);
		
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
